<!-- 文章管理 -->
<template>
  <ContainerSlot>
    <template v-if='!addShow' slot="searchModule">
      <SearchForm :labelWidth="'120px'" :formConfig="formConfig" :formData="formData" :slotList="slotList"
        ref="ruleForm">
        <template slot="searchBtn">
          <el-button type="primary" @click.prevent="search()">查询</el-button>
        </template>
        <template slot="resetBtn">
          <el-button @click.prevent="resetForm()">重置</el-button>
        </template>
      </SearchForm>
    </template>
    <template slot="operationModule">
      <el-button v-show='!addShow' class="opt" type="primary" plain @click="addArticle">
        <i class="el-icon-circle-plus-outline"></i>
        新建
      </el-button>
    </template>
    <template slot="contentModule">
      <div v-show='!addShow' class="article-box">
        <div class="category">
          <CategoryBar class="noIcon" :categoryList="categoryList" @categoryBar="categoryBarFn" />
          <CategoryBar :categoryList="categoryTypeList" @categoryBar="categoryBarTypeFn" />
        </div>
        <div class="article" v-loading="loading">
          <div class="card" v-for="item in articleList" :key="item.id">
            <div class="cardLeft" :class="{ cover: auditStatus == 0 }">
              <div class="title">
                <span class="title-txt" @click="loadArticleDetail(item)">{{ item.title }}</span>
                <span class="time">发布时间：{{ item.createTime }}</span>
                <span class="user">
                  <span>
                    <i class="el-icon-user"></i>
                    {{ item.createUserName }}
                  </span>
                  <span>
                    <i class="el-icon-view"></i>
                    {{ item.watchNum }}
                  </span>
                </span>
              </div>
              <div class="content">{{ item.contentNoImg }}</div>
            </div>
            <div class="cardBtnOne" v-show="auditStatus == 0">
              <el-button type="primary" @click="handleEdit(item)">修改</el-button>
              <el-button class="ml-20" type="danger" @click="handleDelete(item)">删除</el-button>
            </div>
            <div class="cardBtn cardRight" v-show="auditStatus == 1">
              <div>
                <div class="mb-20">审核人：{{ item.auditUserName }}</div>
                <div>审核日期：{{ item.auditDate }}</div>
              </div>
              <el-button class="ml-20" type="danger" @click="handleDelete(item)">删除</el-button>
            </div>
            <div class="cardBtn" v-show="auditStatus == 2">
              <el-button type="primary" @click="handleEdit(item)">修改</el-button>
              <el-button type="primary" @click="handleSubmit(item)">再次提交审核</el-button>
              <el-button type="warning" @click="loadReason(item)">未通过原因</el-button>
              <el-button type="danger" @click="handleDelete(item)">删除</el-button>
            </div>
          </div>

          <div class="noData" v-show="articleList.length == 0">
            暂无数据
          </div>
        </div>
      </div>
    </template>
    <template slot="footerModule">
      <el-pagination v-show='!addShow' @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        background :page-size="pageSize" :page-sizes="[10, 20, 30]" layout="prev, pager, next, jumper" :total="total">
      </el-pagination>
    </template>

    <template v-if="addShow">
      <template slot="operationModule">
        <div class="mt-20" style="margin-right: 2%;">
          <el-button v-show="!articleVisible" type="primary" @click="submitAdd()">提交审核</el-button>
          <el-button v-show="!articleVisible && nowChanceStau == 'editAndAudit'" type="primary" @click="submitAdd('edit')">完成修改</el-button>
          <el-button @click="cancelAdd">返回</el-button>
        </div>
      </template>
      <template slot="contentModule">
        <el-form
          ref="addForm"
          label-position="right"
          :model="addForm"
          class="addForm"
          :rules="addRules"
          label-width="120px"
        >
          <el-form-item label="文章标题:" prop="title" class="w50p">
            <el-input
              v-model="addForm.title"
              :disabled="articleVisible"
              clearable
            />
          </el-form-item>
          <el-form-item label="知识类型:" prop="knowTypeId" class="w50p">
            <el-select v-model="addForm.knowTypeId" placeholder="请选择知识类型" :disabled="articleVisible" style="width: 100%;">
              <el-option v-for="item in categoryTypeList" :key="item.value" :label="item.name" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章正文:" prop="content" class="editorItem">
            <Editor class="quillEditor" :disabled="articleVisible"
              v-model="addForm.content" :quillIndex="20" toref="Editorc" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <el-upload
          v-show="false"
          class="img-uploader"
          :accept="acept"
          action="/xxx"
          :http-request="imgRequest"
        />
        <el-upload
          v-show="false"
          class="video-uploader"
          :accept="acct"
          action="/xxx"
          :http-request="videoRequest"
        />
      </template>
    </template>
  </ContainerSlot>
</template>

<script>
import ContainerSlot from '@/components/Container'
import SearchForm from '@/components/Form'
import Table from '@/components/Table'
import CategoryBar from '@/components/CategoryBar'
import Editor from '@/components/Quill'

import articleApi from "@/api/breed-aquatics-popular/knowledge-base-management/knowledge-classification-management"
import articleExamineApi from "@/api/breed-aquatics-popular/knowledge-base-management/article-examine"
import DocumentApi from "@/api/document"
import config from '@/api/config'

export default {
  name: '',
  components: { ContainerSlot, SearchForm, Table, CategoryBar, Editor },
  data (v) {
    return {
      addShow: false,
      articleVisible: false,
      nowChanceStau: '',
      loading: false,
      uploading: false,
      // 表单配置
      formConfig: [
        {
          label: '文章关键词',
          prop: 'name',
          type: 'input',
          width: '150px'
        },
        {
          label: '发布日期',
          prop: 'date',
          type: 'daterange',
          width: '240px'
        }
      ],
      //插槽
      slotList: [{
        slotName: 'searchBtn'
      },
      {
        slotName: 'resetBtn'
      }],
      // 表单数据
      formData: {
        name: '',
        date: [],
      },
      categoryList: [
        { id: 1, mark: 'status', name: "待审核", value: 0 },
        { id: 2, mark: 'status', name: "审核通过", value: 1 },
        { id: 3, mark: 'status', name: "审核未通过", value: 2 },
      ],
      auditStatus: 0,
      // 分类
      categoryTypeList: [],
      knowTypeId: null,
      // 文章
      articleList: [],
      firstLoad: true,
      // 分页
      total: 0,
      currentPage: 1,
      pageSize: 10,
      // 新增
      addForm: {
        title: '', knowTypeId: '', content: ''
      },
      addRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: ['change', 'blur'] },
        ],
        knowTypeId: [
          { required: true, message: '请选择知识类型', trigger: ['change', 'blur'] },
        ],
        content: [
          { required: true, message: '请输入文章正文', trigger: ['change', 'blur'] },
        ],
      },
      editorOption: {
        modules: {
            toolbar: {
                container: [
                  // ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
                  // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
                  // [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
                  // [{ font: [] }], // 字体种类
                  // //[{ align: [] }], // 对齐方式
                  // ["clean"], // 清除文本格式
                  ["image", "video"] // 链接、图片、视频
                ], //工具菜单栏配置
                handlers: {
                  // 重写图片上传方法
                  image: function(value) {
                    if (!v.articleVisible && value) {
                      // 触发input框选择图片文件
                      document.querySelector(".img-uploader input").click();
                    } else {
                      this.quill.format('image', false);
                    }
                  },
                  // 重写视频上传方法
                  video: function(value) {
                    if (!v.articleVisible && value) {
                      // 触发input框选择图片文件
                      document.querySelector(".video-uploader input").click();
                    }
                  }
                }
            }
        },
        placeholder: '',
        readyOnly: false,
        theme: 'snow', //主题 snow/bubble
      },
      acept: '',
      acct: '',
    }
  },
  computed: {
    editor() {
      return this.$refs.myTextEditor.quillEditor;
    }
  },
  mounted() {
    this.getTypeList()
  },
  methods: {
    // 获取知识分类
    getTypeList() {
      articleApi.queryByCondition({name: ''}).then(res => {
        this.categoryTypeList = res.data.map((el, i) => {
          return { id: i+1, mark: 'status', name: el.name, value: el.knowTypeId }
        })
        this.knowTypeId = res.data[0].knowTypeId
        this.queryPageList()
      })
    },
    // 请求文章列表
    queryPageList() {
      this.loading = true
      articleExamineApi.queryPageByCondition({
        page: this.currentPage,
        size: this.pageSize,
        condition: {
          auditStatus: this.auditStatus,
          knowTypeId: this.knowTypeId,
          content: this.formData.name,
          beginTime: this.formData.date && this.formData.date[0] && this.formData.date[0] + ' 00:00:00',
          endTime: this.formData.date && this.formData.date[1] && this.formData.date[1] + ' 23:59:59'
        }
      }).then(res => {
        let { data } = res
        data.content.map(el => {
          el.contentNoImg = el.content.replace(/<.*?>/ig,"")
        })
        this.articleList = data.content
        this.total = data.totalElements
        this.firstLoad = false
        this.loading = false
      }).catch(() => {
        this.firstLoad = false
        this.loading = false
      })
    },
    // 搜索
    search() {
      this.currentPage = 1
      this.queryPageList()
    },
    resetForm () {
      this.$refs.ruleForm.resetForm()
      this.search()
    },
    // 新增
    addArticle() {
      this.nowChanceStau = 'add';
      this.addShow = true
      this.articleVisible = false
    },
    handleEdit(row) {
      this.nowChanceStau = 'editAndAudit';
      this.addForm = { ...row }
      this.addShow = true
    },
    handleSubmit(row) {
      this.$confirm("再次提交审核，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      }).then(() => {
        let param = { ...row }
        param.auditStatus = 0
        articleExamineApi.editAndAudit(param).then(res => {
          if (res.code == 200) {
            this.$message.success(res.msg)
            this.cancelAdd()
            this.queryPageList()
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    cancelAdd() {
      this.addShow = false
      this.articleVisible = false
      this.addForm = {}
    },
    submitAdd(stau) {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let api = stau || this.nowChanceStau
          let param = { ...this.addForm }
          param.auditStatus = 0
          param.contentSnapshot = param.content.replace(/<.*?>/ig,"")
          articleExamineApi[api](param).then(res => {
            if (res.code == 200) {
              this.$message.success(res.msg)
              this.cancelAdd()
              this.queryPageList()
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        articleExamineApi.del({
          id: row.articleId
        }).then(res => {
          if (res.code == 200) {
            this.queryPageList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            });
          }
        })
      })
    },
    // 分页
    handleCurrentChange (e) {
      this.currentPage = e
      this.queryPageList()
    },
    handleSizeChange (e) {
      this.pageSize = e
      this.queryPageList()
    },
    categoryBarFn (item) {
      this.auditStatus = ''
      if (item.mark === 'status') this.auditStatus = item.value
      this.currentPage = 1
      !this.firstLoad && this.queryPageList()
    },
    categoryBarTypeFn (item) {
      this.status = ''
      if (item.mark === 'status') this.knowTypeId = item.value
      this.currentPage = 1
      !this.firstLoad && this.queryPageList()
    },
    loadReason(row) {
      this.$alert(row.auditRemark, '未通过原因', {
        confirmButtonText: '确定'
      });
    },
    // 文章详情
    loadArticleDetail(row) {
      this.addForm = row
      this.addShow = true
      this.articleVisible = true
    },
    // 图片文件上传
    imgRequest(files) {
      this.uploadRequest(files, "image")
    },
    // 视频
    videoRequest(files) {
      this.uploadRequest(files, "video")
    },
    // 上传文件
    uploadRequest(files, type) {
      let { file } = files
      let dataForm = new FormData()
      dataForm.append('file', file)
      dataForm.append('moduleType', 'SCIENCE_ARTICLE')
      this.uploading = true
      DocumentApi.getUploadUrl(dataForm).then(res => {
        this.uploading = false
        let filePath = res.data
        let quill = this.$refs.myQuillEditor.quill
        let length = quill.getSelection().index
        // 插入视频
        quill.insertEmbed(length, type, config.webServiceUrl+filePath)
        // 调整光标到最后
        quill.setSelection(length + 1);
      }).catch(() => {
        this.$message.error('上传失败！')
        this.uploading = false
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.formList {
  position: relative;
  .search {
    position: absolute;
    top: 0;
    right: 10px;
  }
  .subLabel {
    color: #6f7374;
  }
}
.article-box {
  border: 1px solid #639eda;
  margin-top: 24px;
  height: calc(100% - 30px);
  ::v-deep .noIcon {
    margin-top: -25px;
    .btn-item {
      background: #fff;
    }
    .arrow-left {
      visibility: hidden !important;
    }
    .arrow-right {
      visibility: hidden !important;
    }
  }
  .article {
    height: calc(100% - 100px);
    overflow: auto;
    .card {
      display: flex;
      padding: 15px 10px;
      border-bottom: 1px dashed #639eda;
      &:last-child {
        border-bottom: none;
      }
      .cardLeft {
        max-width: calc(100% - 350px);
        flex: 1;
        &.cover {
          max-width: calc(100% - 200px);
        }
        .title {
          span {
            font-size: 16px;
            color: #6f7374;
            &.title-txt {
              color: #639eda;
              font-size: 22px;
              cursor: pointer;
            }
            &.time {
              margin-left: 20px;
            }
            &.user {
              float: right;
              &>span:first-child {
                margin-right: 15px;
              }
            }
          }
        }
        .content {
          margin-top: 10px;
          text-indent: 2em;
          line-height: 24px;
          display: -webkit-box;
          overflow: hidden;
          text-overflow: ellipsis;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }
      }
      .cardBtn {
        width: 350px;
        display: flex;
        flex-direction: row;
        // justify-content: center;
        margin-left: 30px;
        align-items: center;
      }
      .cardRight {
        width: 300px;
        font-weight: bold;
        font-size: 16px;
        margin-left: 50px;
        color: #6f7374;
      }
      .cardBtnOne {
        width: 200px;
        text-align: center;
      }
    }
    .noData {
      margin-top: 30px;
      text-align: center;
      font-size: 16px;
    }
  }
}
.addForm {
  height: 100%;
  font-size: 0;
  .w50p {
    display: inline-block;
    width: 49%;
  }
  .editorItem {
    height: 100%;
    ::v-deep .el-form-item__content {
      height: 100%;
      .quillEditor {
        height: calc(100% - 120px);
        margin-right: 2%;
        .quill-editor {
          height: 100%;
          .ql-container {
            height: 100%;
          }
        }
      }
    }
  }
}
::v-deep .ql-editor {
  .ql-video {
    display: block;
    max-width: 50%;
  }
}

</style>
